<?php
/**
 * login.php
 *
 * 登陆页面接口
 * 包括登陆接口、验证码获取接口、验证码校验接口、修改密码接口
 */

/**
 * 包含文件
 */


define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');#加载全站初始化配置文件
require_once (dirname(__FILE__) .'/includes/Response.php');#json生成类
function mb_strlen($str,$encoding="utf8")  {
    $step = $encoding=="utf8"?2:1;
    $count = 0;//字数
    $strlen = strlen($str);
    for($i=0;$i<$strlen;$i++){
        $count++;
        if(ord($str{$i})>=128){
            $i=$i+$step;
        }
    }
    return $count;
}


include "./ali/TopSdk.php";
//$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';
/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{   

    if ($_SERVER["PHP_SELF"]='/login.php/act=up_user_pic') {
    require_once(dirname(__FILE__) .'/includes/picture.php');
    $user_pic = picture::uploaddir($_FILES['user_pic']['name'],$_FILES['user_pic']['tmp_name']);

    }else{
       $_REQUEST['act'] = 'login'; 
    }

    
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}



/* 初始化 $exc 对象 */
session_start();

//登陆接口
if ($_REQUEST['act'] == 'login')
{

    $_POST['user_id'] = isset($_POST['user_id']) ? trim($_POST['user_id']) : '';
    $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $_POST['password'] = isset($_POST['password']) ? trim($_POST['password']) : '';
    $_POST['registration_id'] = isset($_POST['registration_id']) ? trim($_POST['registration_id']) : '';
//    $_POST['phone'] = 12356465;
//    $_POST['user_id'] = 1;
//    $_POST['password'] = 123456;

    $sql="SELECT `random` FROM ". $ecs->table('user') ."WHERE phone = '" . $_POST['phone']."' ". "OR user_id = '" . $_POST['user_id']."' " ;
    $random =$db->getOne($sql);
    if(!empty($random))
    {
        /* 检查密码是否正确 */
        $sql = "SELECT user_id, user_name, password, user_sex, user_pic, user_sign, emotion, birth, constellation, hometown, address, random, join_date, phone".
            " FROM " . $ecs->table('user') .
            " WHERE ( phone = '" . $_POST['phone']."' ". "OR user_id = '" . $_POST['user_id']."' )". " AND password = '" . md5(md5($_POST['password']).$random) . "'";
    }
    else
    {
        /* 检查密码是否正确 */
        $sql = "SELECT user_id, user_name, password, user_sex, user_pic, user_sign, emotion, birth, constellation, hometown, address, random, join_date, phone".
            " FROM " . $ecs->table('user') .
            " WHERE ( phone = '" . $_POST['phone']."' ". "OR user_id = '" . $_POST['user_id']."' )". " AND password = '" . md5($_POST['password']) . "'";
    }
    $row = $db->getRow($sql);

    if ($row)
    {
        $sql = "insert into ". $ecs->table('registration_id'). " (user_id,registration_id) values('" .$row['user_id']."','".$_POST['registration_id']."')";
        return Response::json(200,"数据接收成功",$row);

    }
    else
    {
        return Response::json(400,"数据接收失败");
    }
}elseif ($_REQUEST['act'] == 'up_user_pic') {
    //require_once(dirname(__FILE__) .'./includes/upload.php');
     require_once(dirname(__FILE__) .'/includes/picture.php');
    $user_pic = picture::uploaddir($_FILES['user_pic']['name'],$_FILES['user_pic']['tmp_name']);
    
}
elseif ($_REQUEST['act'] == 'act_register') {
    $username = isset($_REQUEST['user_name']) ? trim($_REQUEST['user_name']) : '';
    $birth = isset($_REQUEST['birth']) ? trim($_REQUEST['birth']) : '';
    $address = isset($_REQUEST['address']) ? trim($_REQUEST['address']) : '';
    $sex = isset($_REQUEST['sex']) ? trim($_REQUEST['sex']) : '';
    //$user_pic = picture::uploaddir($_FILES['user_pic']['name'],$_FILES['user_pic']['tmp_name']);
    $user_pic = isset($_REQUEST['user_pic']) ? trim($_REQUEST['user_pic']) : '';
    $password = isset($_REQUEST['password']) ? trim($_REQUEST['password']) : '';
    $phone = isset($_REQUEST['phone']) ? trim($_REQUEST['phone']) : '';
    $joindate = date('Ymd');

    if (empty($username)) {
        return Response::json(401, "用户名不能为空", $username);
    }
    else if (mb_strlen($username,'UTF8')  > 10){
        return Response::json(409,"用户名长度长度不可超过10位",$username);
    }
    if (empty($birth)) {
        return Response::json(402, "生日不能为空", $birth);
    }
    if (empty($address)) {
        return Response::json(403, "常住地不能为空", $address);
    }
    if (empty($sex)) {
        return Response::json(404, "性别不能为空", $sex);
    }
    if (empty($user_pic)) {
        return Response::json(405, "头像不能为空",$user_pic);
    }
    if(empty($phone)){
        return Response::json(406,"手机号不能为空",$phone);
    } else if (!is_numeric($phone)||strlen($phone) != 11) {
        return Response::json(413, "手机号不合法", $phone);
    } else if (user_is_exist($phone)) {
        return Response::json(408, "该手机号已被注册", $phone);
    }

    if (strlen($password) < 6)
    {
        Response::json(411,"密码长度不能小于6位",$password);
    }

    if (strpos($password, ' ') > 0)
    {
        Response::json(412,"密码不合法",$password);
    }
    $random=rand(1,9999);
    $password=md5(md5($password).$random);
    $sql = "INSERT INTO ". $ecs->table('user') . " (user_name, birth,address,user_sex,user_pic,phone,password,random,join_date)". VALUES."('$username','$birth','$address','$sex','$user_pic','$phone','$password','$random','$joindate')" ;
    $db->query($sql);
    $rows = mysql_affected_rows();
    $sql = "SELECT * FROM ".$ecs->table('user')."WHERE phone ='$phone'";
    $row = $db->getRow($sql);

    if($rows > 0){
        Response::json(201,"数据上传成功",$row);
    }
    else{
        Response::json(430,"数据上传失败",$row);
    }


}
elseif ($_REQUEST['act'] == 'pw_get_code') {

    $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $temp_id = isset($_POST['temp_id']) ? trim($_POST['temp_id']) : '';
    $sql = "SELECT `phone` FROM " . $ecs->table('user') . "WHERE phone = '" . $_POST['phone'] . "' ";
    $mobile = $db->getOne($sql);

    if (!empty($mobile)) {
        $pw_verification_code = generate_verification_code();
        $code = $pw_verification_code;
        $_SESSION['phone'] = $mobile;
        $_SESSION['code'] = $pw_verification_code;
        $c = new TopClient;
        $c->appkey = '23498041';
        $c->secretKey = '0cc7671892750c1e147a925bc9ae2577';
        $c->format = "json";
        $req = new AlibabaAliqinFcSmsNumSendRequest;
        $req->setSmsType("normal");
        $req->setSmsFreeSignName("兜伴科技");
        $req->setSmsParam("{\"code\":\"" . $code . "\"}");
        $req->setRecNum($mobile);
        $req->setSmsTemplateCode($temp_id);
        $resp = $c->execute($req);
        return $resp;


    } else {
        return Response::json(420, "手机号未注册", $mobile);
    }
}
//elseif ($_REQUEST['act'] == 'pw_get_code') {
//
//    $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
////    $_POST['phone'] = '18660511915';
//    $temp_id = isset($_POST['temp_id']) ? trim($_POST['temp_id']) : '';
//    $sql = "SELECT `phone` FROM " . $ecs->table('user') . "WHERE phone = '" . $_POST['phone'] . "' ";
//    $mobile = $db->getOne($sql);
//
//    if (!empty($mobile)) {
//        $url = 'https://api.sms.jpush.cn/v1/codes';
//        $appKey_pw = 'd2f6ff28deeaec1233c2287d:31d3d9b8cc8944f367ac8946';
//        $base64=base64_encode($appKey_pw);
//        $arr = array(
//            'mobile' => $mobile,
//            'temp_id' => '*');
//        $param = json_encode($arr);
//        $head = array("Authorization:Basic $base64","Content-Type:application/json");
//        $result = get_validate_code::request_post($url, $param, $head);
//        $data = json_decode($result);
////        echo $result;
//        return $result;
//    } else {
//        return Response::json(420, "手机号未注册", $mobile);
//    }
//}
//注册获取验证码接口 参数手机号 短信模板 成功返回成功标记 手机接到验证码
elseif ($_REQUEST['act'] == 'reg_get_code') {
    $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    //$temp_id = isset($_POST['temp_id']) ? trim($_POST['temp_id']) : '';
    $temp_id='SMS_24515118';
    $mobile = $_POST['phone'];
    //$mobile = '18669723768';

    if(empty($mobile)){
        return Response::json(406,"手机号不能为空",$mobile);
    } else if (!is_numeric($mobile)||strlen($mobile) != 11) {
        return Response::json(413, "手机号不合法", $mobile);
    } else if (user_is_exist($mobile)) {
        return Response::json(408, "该手机号已被注册", $mobile);
    }
    $reg_verification_code = generate_verification_code();
    $_SESSION['code'] = $reg_verification_code;
    $_SESSION['phone'] = $mobile;
    $code = $reg_verification_code;
    $c = new TopClient;
    $c->appkey = '23498041';
    $c->secretKey = '0cc7671892750c1e147a925bc9ae2577';
    $c->format = "json";
    $req = new AlibabaAliqinFcSmsNumSendRequest;
    $req->setSmsType("normal");
    $req->setSmsFreeSignName("兜伴科技");
    $req->setSmsParam("{\"code\":\"" . $code . "\"}");
    $req->setRecNum($mobile);
    $req->setSmsTemplateCode($temp_id);
    $resp = $c->execute($req);
    return $resp;
}
//elseif ($_REQUEST['act'] == 'reg_get_code') {
//
//    $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
//    $temp_id = isset($_POST['temp_id']) ? trim($_POST['temp_id']) : '';
//    $mobile = $_POST['phone'];
//    if(empty($phone)){
//        return Response::json(406,"手机号不能为空",$mobile);
//    } else if (!is_numeric($mobile)||strlen($mobile) != 11) {
//        return Response::json(413, "手机号不合法", $mobile);
//    } else if (user_is_exist($mobile)) {
//        return Response::json(408, "该手机号已被注册", $mobile);
//    }
////    $sql = "SELECT `phone` FROM " . $ecs->table('user') . "WHERE phone = '" . $_POST['phone'] . "' ";
////    $mobile = $db->getOne($sql);
//
//    $url = 'https://api.sms.jpush.cn/v1/codes';
//    $appKey_pw = 'd2f6ff28deeaec1233c2287d:31d3d9b8cc8944f367ac8946';
//    $base64 = base64_encode($appKey_pw);
//    $arr = array(
//        'mobile' => $mobile,
//        'temp_id' => '*');
//    $param = json_encode($arr);
//    $head = array("Authorization:Basic $base64", "Content-Type:application/json");
//    $result = get_validate_code::request_post($url, $param, $head);
//    $data = json_decode($result);
////        echo $result;
//    return $result;
//    }
//$_SESSION['phone'] == $_POST['phone'] && $_SESSION['code'] == $_POST['validate_code']

//验证接口 参数：验证码
elseif($_REQUEST['act'] == 'verify'){
    $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $_POST['validate_code'] = isset($_POST['validate_code']) ? trim($_POST['validate_code']) : '';
    if($_POST['validate_code'] == $_SESSION['code'] && $_POST['phone'] == $_SESSION['phone']){
        $result = true;
        return Response::json(202, "验证成功", $result);

    }else{
        $result = false;
        return Response::json(421, "验证失败", $result);
    }


//    global $data;
//    $url = 'https://api.sms.jpush.cn/v1/codes/'.$data['msg_id'].'/valid ';
//    $param = array(
//        'code' => $_POST['validate_code']
//    );
//    $verification_result = verify::request_post($url,$param);
//
//    $res = json_decode($verification_result);
//    return $verification_result;
}
//
//密码修改接口 参数 手机号 新密码
    if($_REQUEST['act'] == 'update_pw'){
        $_POST['phone'] = isset($_POST['phone']) ? trim($_POST['phone']) : '';
        $_POST['user_id'] = isset($_POST['user_id']) ? trim($_POST['user_id']) : '';
        $_POST['new_password'] = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
        $random = rand(1,999999);
        $new_password = md5(md5($_POST['new_password']).$random);
        $sql = "UPDATE ". $ecs->table('user') ."SET password = '". $new_password ."' , random = '".$random ."' WHERE user_id = '" .$_POST['user_id']."'";
        $row = $db->query($sql);
        if(!empty($row)) {
            return Response::json(203, "密码修改成功");
        }else{
            return Response::json(422, "密码修改失败");
        }

    }



function user_is_exist($phone)
{
    $sql = "SELECT user_name FROM " . $GLOBALS['ecs']->table('user') . "WHERE phone ='$phone'";
    $result = $GLOBALS['db']->query($sql);
    $rows = mysql_num_rows($result);
    if ($rows > 0) {
        return true;
    } else {
        return false;
    }

}

function generate_verification_code()
{
    $random = rand(100000,999999);
    return $random;
}



/**
 * Created by PhpStorm.
 * User: tuhao
 * Date: 2016/10/24
 * Time: 16:30
 */